package ${package}.dao;

import ${package}.model.entity.Authority;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 * AuthorityDao implementation.
 */
@Repository
public class AuthorityDaoImpl implements AuthorityDao {
    /**
     * Dao logger.
     */
    private Log logger = LogFactory.getLog(this.getClass());

    /**
     * JPA persistence context.
     */
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * Dao info string.
     */
    public static final String DAO_INFO = AuthorityDaoImpl.class.getName() + ", $Revision: $";


    @Override
    public String getDaoInfo() {
        logger.debug(AuthorityDaoImpl.class.getName() + " Info requested.");

        return DAO_INFO;
    }

    @Override
    public void save(Authority authority) {
        logger.debug("Persisting authority: " + authority.getAuthority());
        entityManager.persist(authority);
    }

    @Override
    public void delete(Authority authority) {
        logger.debug("Removing authority: " + authority.getAuthority());
        entityManager.remove(authority);
    }

    @Override
    public Authority getByAuthority(String authority) {
        logger.debug("Retrieving authority: " + authority);

        Authority a = null;
        try {
            a = (Authority) entityManager.createQuery(
                    "SELECT a FROM Authority a WHERE a.authority = :authority").setParameter("authority", authority).getSingleResult();
        } catch (NoResultException e) {
            logger.debug("no authority found: " + authority);
        }
        return a;
    }
}
